package com.future.direction.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.graphics.ColorUtils;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.future.direction.R;
import com.future.direction.common.util.BannerImageLoader;
import com.future.direction.common.util.ColorInfo;
import com.future.direction.common.util.StatusBarUtil;
import com.future.direction.di.component.AppComponent;
import com.future.direction.presenter.MainHomePresenter;
import com.future.direction.ui.activity.ChosePayWayActivity;
import com.future.direction.ui.activity.CourseDailyBusinessActivity;
import com.future.direction.ui.activity.CourseFreeTrialActivity;
import com.future.direction.ui.activity.EMBAOnlineActivity;
import com.future.direction.ui.activity.SearchActivity;
import com.future.direction.ui.widget.PinnedHeaderListView;
import com.liaoinstan.springview.container.DefaultFooter;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Created by zhangpeng on 2019/11/06.
 */
public class MainHomeFragment extends BaseFragment<MainHomePresenter> implements View.OnClickListener {


    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.springView)
    SpringView springView;
    @BindView(R.id.iv_header_bg)
    ImageView ivHeaderBg;
    @BindView(R.id.nestedScrollView_home)
    NestedScrollView nestedScrollViewHome;
    @BindView(R.id.view_status_bar)
    View viewStatusBar;
    @BindView(R.id.ll_title_search)
    LinearLayout llTitleSearch;
    @BindView(R.id.tv_title_header)
    TextView tvTitleHeader;
    @BindView(R.id.tv_all_course)
    TextView tvAllCourse;
    @BindView(R.id.tv_enterprise_increase)
    TextView tvEnterpriseIncrease;
    @BindView(R.id.tv_online_emba)
    TextView tvOnlineEmba;
    @BindView(R.id.tv_below_the_line)
    TextView tvBelowTheLine;
    @BindView(R.id.recycle_uprising)
    RecyclerView recycleUprising;
    @BindView(R.id.phlv)
    PinnedHeaderListView phlv;
    @BindView(R.id.tv_daily_business)
    TextView tvDailyBusiness;
    @BindView(R.id.tv_free_trial)
    TextView tvFreeTrial;
    Unbinder unbinder;


    private int pageNumber = 1;
    private int pageSize = 10;
    private int count;
    private List<String> bannerList = new ArrayList<>();
    private List<ColorInfo> colorList = new ArrayList<>();
    private BannerImageLoader imageLoader;
    private boolean isInit = true;
    private int statusBarHeight;


    @Override
    public int setLayout() {
        return R.layout.fragment_home;
    }

    @Override
    protected void getExtras() {

    }


    @Override
    public void init() {
        statusBarHeight = StatusBarUtil.getStatusBarHeight(getActivity());
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) viewStatusBar.getLayoutParams();
        params.height = statusBarHeight;
        viewStatusBar.setLayoutParams(params);

        springView.setHeader(new DefaultHeader(getContext()));//设置刷新头
        springView.setFooter(new DefaultFooter(getContext()));//设置加载尾
        initView();
        initBanner();
        initRecycle();


    }

    private void initView() {

        banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (positionOffset > 1) {//会出现极个别大于1的数据
                    return;
                }
                //修正position，解决两头颜色错乱，来自Banner控件源码
                if (position == 0) {
                    position = count;
                }
                if (position > count) {
                    position = 1;
                }
                int pos = (position + 1) % count;//很关键

                int vibrantColor = ColorUtils.blendARGB(imageLoader.getVibrantColor(pos), imageLoader.getVibrantColor(pos + 1), positionOffset);
                ivHeaderBg.setBackgroundColor(vibrantColor);
//                setStatusBarColor(getActivity(), vibrantColor);
            }

            @Override
            public void onPageSelected(final int position) {

                if (isInit) {// 第一次,延时加载才能拿到颜色
                    isInit = false;
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            int vibrantColor = imageLoader.getVibrantColor(1);
                            ivHeaderBg.setBackgroundColor(vibrantColor);
//                            setStatusBarColor(getActivity(), vibrantColor);
                        }
                    }, 200);

                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });


    }

    private void initRecycle() {

//        StaggeredGridLayoutManager gridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
//        recycleHome.setLayoutManager(gridLayoutManager);
//        recycleHome.setNestedScrollingEnabled(false);//禁止滑动
//        recycleHome.setHasFixedSize(true);
//        recycleHome.setFocusable(false);//禁止获取焦点
//        homeAdapter = new HomeAdapter(null);
//        recycleHome.setAdapter(homeAdapter);

    }


    @Override
    protected void setListener() {


        tvAllCourse.setOnClickListener(this);
        llTitleSearch.setOnClickListener(this);
        tvDailyBusiness.setOnClickListener(this);
        tvFreeTrial.setOnClickListener(this);
        tvOnlineEmba.setOnClickListener(this);
        springView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                pageNumber = 1;

            }

            @Override
            public void onLoadmore() {
                pageNumber++;

            }
        });
        nestedScrollViewHome.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {


                int height = banner.getHeight() + statusBarHeight;
                if (scrollY <= height) {
                    llTitleSearch.setVisibility(View.VISIBLE);
                    //viewStatusBar.setBackgroundColor(getActivity().getResources().getColor(R.color.colorWhite00));
                    tvTitleHeader.setVisibility(View.GONE);
                    setStatusBarColor(getActivity(), getActivity().getResources().getColor(R.color.colorWhite00));
                    StatusBarUtil.setStatusTextColor(false, getActivity());

                } else {
                    llTitleSearch.setVisibility(View.GONE);
                    // viewStatusBar.setBackgroundColor(getActivity().getResources().getColor(R.color.colorWhite));
                    tvTitleHeader.setVisibility(View.VISIBLE);
                    setStatusBarColor(getActivity(), getActivity().getResources().getColor(R.color.colorWhite));
                    StatusBarUtil.setStatusTextColor(true, getActivity());

                }

            }
        });

    }

    @Override
    public void setupAcitivtyComponent(AppComponent appComponent) {

    }


    /**
     * 初始化banner
     */
    private void initBanner() {
//        bannerList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1556532613936&di=3769695217e3424f18c3d23966ecd4dc&imgtype=0&src=http%3A%2F%2Fpic.90sjimg.com%2Fback_pic%2Fqk%2Fback_origin_pic%2F00%2F04%2F19%2F70e2846ebc02ae10161f25bf7f5461a1.jpg");
        bannerList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1556532613936&di=4dd453940f49d9801826e6b820490957&imgtype=0&src=http%3A%2F%2Fpic161.nipic.com%2Ffile%2F20180410%2F26429156_154754410034_2.jpg");
        bannerList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1556532665664&di=9ead9eb8a9fe2af9a01b0dd39f3e41f4&imgtype=0&src=http%3A%2F%2Fbpic.588ku.com%2Fback_pic%2F05%2F37%2F28%2F475a43591370453.jpg");
        bannerList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1556532613934&di=0be1c6bbf0441bd19ef6d4e3ce799263&imgtype=0&src=http%3A%2F%2Fpic96.nipic.com%2Ffile%2F20160430%2F7036970_215739900000_2.jpg");
        bannerList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1556532613935&di=39c387012e3d8fa2eef90129eaf83c5c&imgtype=0&src=http%3A%2F%2Fpic25.nipic.com%2F20121211%2F7031681_170238437383_2.jpg");
        count = bannerList.size();
        colorList.clear();
        for (int i = 0; i <= count + 1; i++) {
            ColorInfo info = new ColorInfo();
            if (i == 0) {
                info.setImgUrl(bannerList.get(count - 1));
            } else if (i == count + 1) {
                info.setImgUrl(bannerList.get(0));
            } else {
                info.setImgUrl(bannerList.get(i - 1));
            }
            colorList.add(info);
        }

        imageLoader = new BannerImageLoader(colorList);
        banner.setImageLoader(imageLoader);
        //设置图片集合
        banner.setImages(bannerList);
        //设置banner动画效果
        // banner.setBannerAnimation(Transformer.DepthPage);
        //设置轮播时间
        banner.setDelayTime(3000);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

            }
        });
        //banner设置方法全部调用完毕时最后调用
        banner.start();

    }

    /**
     * 设置状态栏颜色
     *
     * @param activity
     */
    public static void setStatusBarColor(Activity activity, int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            //状态栏改变颜色。
            window.setStatusBarColor(color);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_all_course:
                Intent intent = new Intent(getContext(), ChosePayWayActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_title_search:
                Intent search = new Intent(getContext(), SearchActivity.class);
                startActivity(search);
                break;

            case R.id.tv_daily_business:
                Intent daily = new Intent(getContext(), CourseDailyBusinessActivity.class);
                startActivity(daily);
                break;

            case R.id.tv_free_trial:
                Intent free = new Intent(getContext(), CourseFreeTrialActivity.class);
                startActivity(free);
                break;

            case R.id.tv_online_emba:
                Intent emba = new Intent(getContext(), EMBAOnlineActivity.class);
                startActivity(emba);
                break;
        }
    }


}
